﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sitecore.Web.UI.Sheer;
using Sitecore.Data.Items;
using Sitecore.Text;
using Sitecore.ChangesTracker.Events;
using Sitecore.ChangesTracker.Archiving;
using Sitecore.Data.Archiving;

namespace Sitecore.ChangesTracker.Commands
{
    class ChangeTemplate : Sitecore.Shell.Framework.Commands.ChangeTemplate
    {
        protected new void Run(ClientPipelineArgs args)
        {
            Guid archivalId = Guid.Empty;
            if (SheerResponse.CheckModified())
            {
                if (args.IsPostBack)
                {
                    ArchiveDisabler.DeactivateForItem(new Guid(args.Parameters["id"]));
                    if (args.Result == "yes")
                    {
                        Context.ClientPage.SendMessage(this, "item:templatechanged");
                    }
                    else
                    {
                        archivalId = new Guid(args.Parameters["archivalId"]);
                        if (archivalId != Guid.Empty)
                        {
                            ChangeTrackerArchive archive = ArchiveManager.Providers["changetracker"].GetArchive("changetracker", Context.ContentDatabase) as ChangeTrackerArchive;
                            ArchiveQuery query2 = new ArchiveQuery
                            {
                                ArchivalId = archivalId
                            };
                            archive.RemoveEntries(query2);
                        }
                    }
                }
                else
                {
                    string str = args.Parameters["id"];
                    Item item = Context.ContentDatabase.Items[str];
                    if (item == null)
                    {
                        SheerResponse.Alert("Item not found.", new string[0]);
                    }
                    else
                    {
                        //ItemEventHandler evtHandler = new ItemEventHandler();
                        //evtHandler.ArchiveItem(item, "Template changed",out archivalId);                                                
                        TrackerManager.ArchiveItem(item, "Template changed", out archivalId);
                        args.Parameters.Add("archivalId", archivalId.ToString());
                        ArchiveDisabler.ActivateForItem(item.ID.ToGuid());
                        UrlString str2 = new UrlString("/sitecore/shell/Applications/Templates/Change template.aspx");
                        str2.Append("id", item.ID.ToString());
                        Context.ClientPage.ClientResponse.ShowModalDialog(str2.ToString(), true);
                        args.WaitForPostBack();
                    }
                }
            }
        }

    }
}
